/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.Advance;
import com.jeeplus.modules.ap.entity.Policy;
import com.jeeplus.modules.ap.service.PolicyService;
import com.jeeplus.modules.ap.util.Export;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.TmsWaybill;
import com.jeeplus.modules.tms.service.TmsWaybillService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.entity.Lnsurance;
import com.jeeplus.modules.ap.service.LnsuranceService;

/**
 * 保险Controller
 * @author 李超辉
 * @version 2018-09-04
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/lnsurance")
public class LnsuranceController extends BaseController {

	@Autowired
	private LnsuranceService lnsuranceService;
	@Autowired
	private TmsWaybillService tmsWaybillService;
	@Autowired
	private PolicyService policyService;
	
	@ModelAttribute
	public Lnsurance get(@RequestParam(required=false) String id) {
		Lnsurance entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = lnsuranceService.get(id);
		}
		if (entity == null){
			entity = new Lnsurance();
		}
		return entity;
	}
	
	/**
	 * 保险列表页面
	 */
	@RequiresPermissions("ap:lnsurance:list")
	@RequestMapping(value = {"list", ""})
	public String list(Model model) {
		List<Policy> list=policyService.findList(new Policy());
        model.addAttribute("ps",list);
		return "modules/ap/2/lnsuranceList";
	}

	/**
	 * 保险列表页面
	 */
	@RequiresPermissions("ap:lnsurance:list")
	@RequestMapping(value = "list1")
	public String list1() {
		return "modules/ap/1/lnsuranceList";
	}

	/**
	 * 保险列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:lnsurance:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Lnsurance lnsurance, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getUseroffice().equals("总部")){
			lnsurance.setPro(UserUtils.getUseroffice());
		}
		Page<Lnsurance> page = lnsuranceService.findPage(new Page<Lnsurance>(request, response), lnsurance);
		return getBootstrapData(page);
	}
	/**
	 * 保险列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:lnsurance:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Lnsurance lnsurance, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getUseroffice().equals("总部")){
			lnsurance.setPro(UserUtils.getUseroffice());
		}
		lnsurance.setStatus("已确认");
		Page<Lnsurance> page = lnsuranceService.findPage(new Page<Lnsurance>(request, response), lnsurance);
		return getBootstrapData(page);
	}
	@ResponseBody
	@RequiresPermissions("ap:policy:list")
	@RequestMapping(value = "cx")
	public String cx(String min,String max,String pro,String bd,String qyd,String dzd,String cph,String ydh) {
          Lnsurance l=new Lnsurance();
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			l.setPro(pro);
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				l.setPro(UserUtils.getUseroffice());
			}
		}
		l.setMin(min);
		l.setMax(max);
		l.setHwmc(bd);
		l.setCph(cph);
		l.setYdh(ydh);
		l.setStart(qyd);
		l.setArrive(dzd);
		l.setStatus("已确认");
		List<Lnsurance> list=lnsuranceService.findList(l);
		double zl=0.0;
		double gsje=0.0;
		String ids="";
		for(Lnsurance ln:list){
           zl+=Double.parseDouble(ln.getZl());
           gsje+=Double.parseDouble(ln.getGsje());
           ids+=ln.getId()+",";
		}
		NumberFormat nf = NumberFormat.getInstance();
       l.setZl(nf.format(zl).replaceAll(",",""));
		l.setGsje(nf.format(gsje).replaceAll(",",""));
		l.setMax(ids);
		list.add(l);
		Gson g=new Gson();
		return g.toJson(list).toString();
	}


	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
		String[] idd=ids.split(",");
		List<Lnsurance> list =new ArrayList<Lnsurance>();
		for(String id:idd){
			list.add(lnsuranceService.get(id));
		}
		Export e=new Export();
		e.exportlnsurance(response,list);
	}
	/**
	 * 查看，增加，编辑保险表单页面
	 */
	@RequiresPermissions(value={"ap:lnsurance:view","ap:lnsurance:add","ap:lnsurance:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Lnsurance lnsurance, Model model) {
		model.addAttribute("lnsurance", lnsurance);
		return "modules/ap/lnsuranceForm";
	}

	/**
	 * 保存保险
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:lnsurance:add","ap:lnsurance:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Lnsurance lnsurance, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, lnsurance)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		lnsuranceService.save(lnsurance);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存保险成功");
		return j;
	}

	/**
	 * 删除保险
	 */
	@ResponseBody
	@RequestMapping(value = "qd")
	public AjaxJson qd(Lnsurance lnsurance, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		lnsurance.setStatus("已确认");
		lnsuranceService.save(lnsurance);
		TmsWaybill bill=tmsWaybillService.get(lnsurance.getPid());
		bill.setBx("已投保");
		tmsWaybillService.save(bill);
		String name=lnsurance.getHwmc();
		Policy p=policyService.findUniqueByProperty("name",name);
		String xf=lnsurance.getGsje();
		String sy=p.getSy();
		NumberFormat nf = NumberFormat.getInstance();
		p.setSy(nf.format(Double.parseDouble(sy)-Double.parseDouble(xf)).replaceAll(",",""));
		policyService.save(p);
		j.setMsg("确认成功");
		return j;
	}

	/**
	 * 删除保险
	 */
	@ResponseBody
	@RequestMapping(value = "qx")
	public AjaxJson qx(Lnsurance lnsurance, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		TmsWaybill t=tmsWaybillService.get(lnsurance.getPid());
		t.setBx("未投保");
       tmsWaybillService.save(t);
		lnsuranceService.delete(lnsurance);
		j.setMsg("取消成功");
		return j;
	}

	/**
	 * 删除保险
	 */
	@ResponseBody
	@RequiresPermissions("ap:lnsurance:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Lnsurance lnsurance, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		lnsuranceService.delete(lnsurance);
		j.setMsg("删除保险成功");
		return j;
	}


	@ResponseBody
	@RequestMapping(value="detil")
	public String  detil(String i){
		Gson  g=new Gson();
		return g.toJson(lnsuranceService.findUniqueByProperty("pid",i)).toString();
	}
	/**
	 * 批量删除保险
	 */
	@ResponseBody
	@RequiresPermissions("ap:lnsurance:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			lnsuranceService.delete(lnsuranceService.get(id));
		}
		j.setMsg("删除保险成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:lnsurance:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Lnsurance lnsurance, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "保险"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Lnsurance> page = lnsuranceService.findPage(new Page<Lnsurance>(request, response, -1), lnsurance);
    		new ExportExcel("保险", Lnsurance.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出保险记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("ap:lnsurance:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Lnsurance> list = ei.getDataList(Lnsurance.class);
			for (Lnsurance lnsurance : list){
				try{
					lnsuranceService.save(lnsurance);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条保险记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条保险记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入保险失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/lnsurance/?repage";
    }
	
	/**
	 * 下载导入保险数据模板
	 */
	@RequiresPermissions("ap:lnsurance:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "保险数据导入模板.xlsx";
    		List<Lnsurance> list = Lists.newArrayList(); 
    		new ExportExcel("保险数据", Lnsurance.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/lnsurance/?repage";
    }

}